import { store } from "../index.js";
import { defineStore } from "pinia";
import { ElMessage } from "element-plus";

const LOGIN_TIMEOUT = 5 * 60; // 登录超时时间，单位秒

export const useUserInfoStore = defineStore("userInfo", {
  state: () => {
    return {
      isLogin: false,
      countDownNumber: LOGIN_TIMEOUT,
      userTips: "",
      username: "",
      realname: "",
      identity: 0,
      realIdentity: 0,
      work_type: 0,
      // 普通员工登录信息缓存
      normalUsername: "",
      normalRealname: "",
      workTypeOptions: [
        { label: "过程点检", value: 0 },
        { label: "小批全检", value: 6 },
        { label: "20件稳定性 / 切换型号", value: 10 },
        { label: "20件稳定性 / 停机恢复", value: 11 },
        { label: "20件稳定性 / 调机确认", value: 12 },
        { label: "20件稳定性 / 砂轮刀具更换", value: 13 }
      ]
    };
  },
  actions: {
    async userLogin() {
      if (!this.username || this.username.length < 7) {
        return {
          code: 1,
          msg: "请先输入完整工号"
        };
      }
      const res = await window.api.login(this.username);
      if (res.code === 0) {
        this.isLogin = true;
        this.realIdentity = res.data.identity;
        this.identity = res.data.identity;
        this.username = res.data.username;
        this.realname = res.data.realname;
        ElMessage({
          message: `登录成功，欢迎使用泵体量仪数据采集系统！`,
          type: "success"
        });
        // this.logoutCountDown()
        if (this.realIdentity > 0) {
          // 高级权限设置自动退出功能
          this.logoutCountDown();
        } else {
          // 缓存普通员工的登录信息
          this.normalRealname = this.realname;
          this.normalUsername = this.username;
        }
      } else {
        console.log(res.data);
        ElMessage.error(res.msg);
      }
      return res;
    },
    logoutCountDown() {
      if (!this.isLogin) {
        this.userTips = "";
        this.countDownNumber = LOGIN_TIMEOUT;
        return;
      }
      this.countDownNumber--;
      if (this.countDownNumber <= 0) {
        ElMessage.info(`账号已失效，请重新登录`);
        if (this.normalUsername) {
          // 将普通员工信息重新登录
          this.username = this.normalUsername;
          this.realname = this.normalRealname;
          this.realIdentity = 0;
          this.identity = 0;
          this.userTips = "";
          this.countDownNumber = LOGIN_TIMEOUT;
          return;
        } else {
          // 退出当前登录用户
          this.userLogout();
        }
      }
      const min = Math.floor(this.countDownNumber / 60);
      const sec = this.countDownNumber % 60;
      this.userTips = `${min}分${sec}秒后自动退出登录`;
      setTimeout(() => {
        this.logoutCountDown();
      }, 1000);
    },
    userLogout() {
      this.isLogin = false;
      this.username = "";
      this.realname = "";
      this.realIdentity = 0;
      this.identity = 0;
    }
  }
});

export function useInfoStoreHook() {
  return useUserInfoStore(store);
}
